package com.book.service.impl;

import com.book.dao.ImgDao;
import com.book.dto.ImgDto;
import com.book.dto.UserDto;
import com.book.helper.ImgHelper;
import com.book.redis.RedisRandomProvider;
import com.book.service.ImgService;
import com.book.pojo.Img;
import com.book.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @Author LiJinCheng
 * @Date 2020/11/17 5:12 下午
 * @Version 1.0
 * @package com.book.service.impl
 **/
@Slf4j
@Service
public class ImgServiceImpl implements ImgService {
    @Resource
    private ImgDao imgDao;
    @Autowired
    private RedisRandomProvider redisRandomProvider;

    @Override
    public String  saveImg(ImgDto img, UserDto userDto, MultipartFile multipartFile) {
        try {
            // 保存图片的路径，图片上传成功后，将路径保存到数据库
            String filePath = Constants.PATH;
            // 获取原始图片的扩展名
            String originalFilename = multipartFile.getOriginalFilename();
            // 生成文件新的名字
            assert originalFilename != null;
            String newFileName = img.getUbCode() + redisRandomProvider.getImgNum() +originalFilename.substring(originalFilename.lastIndexOf("."));
            // 封装上传文件位置的全路径
            filePath = filePath + "/" + userDto.getUCode();
            File targetFile = new File(filePath, newFileName);
            multipartFile.transferTo(targetFile);
            img.setImgUrl(userDto.getUCode()+"/"+newFileName);
            Img img1 = ImgHelper.convertDtoToPo(img);
            log.info("##imgServiceImpl.saveImg##img:{}",img1);
            imgDao.insert(img1);
            return Constants.SUCCESS;
        } catch (IOException e) {
            e.printStackTrace();
            return Constants.ERROR;
        }
    }

    @Override
    public List<String> getImgByBookCode(String ubCode) {
        return imgDao.getImgByBookCode(ubCode);
    }
}
